import * as types from './mutation-types'
import * as constant from '../../common/constant'
import { transform, untransform } from '../../common/uri'
import Vue from 'vue'
import axios from 'axios'
import * as utils from "@/store/yg/common/utils"

axios.defaults.withCredentials = true;

function loadData (state, uri) {
  axios.post(constant.API_SERVER + uri).then(response => {
    state.data = response.data;
  }, error => {
    // error callback
    console.log(error);
  }
  );
}

function loadEntry (state, link, mobile) {
  state.entry = {};
  state.data = {};
  var uri = link;

  uri = untransform(uri);



  /*
    优先加载JS配置，如果无法加载则获取YAML配置
  */
  var e = null;
  try {
    e = require('@/layout/blank' + uri + '/Entry.js');
  } catch (ex) {
  };
  if (e) {
    state.entry = e;
  } else {
    var localStorageTag = mobile ? 'mobile_' : 'blank_'
    if (localStorage[localStorageTag + uri] && !constant.DEV_MODE) {
      state.entry = JSON.parse(localStorage[localStorageTag + uri]);
    }
  }
  var loadUri = '/api/consume/ajax?uri=' + uri;
  if (Object.keys(state.entry).length > 0) {
    if (state.entry.client.get) {
      loadUri += "&f=" + state.entry.client.get;
      loadUri += mobile ? '&type=mobile' : '';
      loadData(state, loadUri);
    }
    return;
  }

  var mainUri = (mobile ? '/api/entry/mobile?uri=' : '/api/entry/blank?uri=') + uri;

  axios.post(constant.API_SERVER + mainUri).then(response => {
    if (response.data) {
      state.entry = response.data;
      localStorage[localStorageTag + uri] = JSON.stringify(state.entry);
      utils.storeSource(state.entry.sources, localStorageTag + uri);
      if (state.entry.client.get) {
        loadUri += "&f=" + state.entry.client.get;
        loadUri += mobile ? '&type=mobile' : '';
        loadData(state, loadUri);
      }
    }
  }, error => {
    // error callback
    console.log(error);
  }
  );

}

export default {
  [types.LOAD_BLANK_ENTRY] (state, link) {
    loadEntry(state, link);
  },
  [types.LOAD_MOBILE_ENTRY] (state, link) {
    loadEntry(state, link, true);
  },
  [types.LOAD_BLANK_PAGE_DATA] (state, req) {
    loadData(state, req);
  },
  [types.SAVE_MOBILE_TITLE] (state, title) {
    state.mobileTitle = title;
    state.message = '';
  },
  [types.COMMIT_MOBILE_PAGE_DATA] (state, req) {
    var uri = '/api/consume/ajax?uri=' + untransform(req.uri) + "&type=mobile";

    for (var k in state.data) {
      if (undefined == state.data[k]) {
        continue;
      }
      state.data[k] = (state.data[k] + '').trim();
    }

    axios({
      method: 'post',
      url: constant.API_SERVER + uri,
      data: state.data
    }).then(response => {
      //state.data = response.data;
      if (req.callafter) {
        req.callafter(response.data)
      }
    }, error => {
      // error callback
      console.log(error);
    }
    );
  },
  [types.MESSAGE_TYPE] (state, req) {

    state.messageType = req;
    console.log('state', state);
  }
};
